package com.atguigu.gulimall.ware.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.StockDetailTo;
import com.atguigu.common.to.mq.StockLockTo;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.atguigu.gulimall.ware.entity.WareOrderTaskEntity;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.feign.OrderFeignService;
import com.atguigu.gulimall.ware.feign.ProductFeignService;
import com.atguigu.gulimall.ware.service.WareOrderTaskDetailService;
import com.atguigu.gulimall.ware.service.WareOrderTaskService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.OrderItemVo;
import com.atguigu.gulimall.ware.vo.OrderVo;
import com.atguigu.gulimall.ware.vo.SkuHasStockVo;
import com.atguigu.gulimall.ware.vo.WareSkuLockVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    WareOrderTaskService wareOrderTaskService;

    @Autowired
    WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    OrderFeignService orderFeignService;
    //处理库存解锁释放


    private void unLockStock(Long skuId,Long wareId,Integer num,Long detailId){

        //库存解锁
         this.baseMapper.unLockStock(skuId,wareId,num);
         //更新库存工作单的状态
        WareOrderTaskDetailEntity entity = new WareOrderTaskDetailEntity();
        entity.setId(detailId);
        entity.setLockStatus(2);
        wareOrderTaskDetailService.updateById(entity);
    }
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if(StringUtils.isNotEmpty(skuId)){
            wrapper.eq("sku_id",skuId);
        }
        String wareId = (String) params.get("wareId");
        if(StringUtils.isNotEmpty(wareId)){
            wrapper.eq("ware_id",wareId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        List<WareSkuEntity> wareSkuEntities = this.baseMapper.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));

        if (wareSkuEntities==null ||wareSkuEntities.size()==0){
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setStockLocked(0);

            //远程查询skuname
        try{
            R info = productFeignService.info(skuId);
            Map<String,Object> skuInfo =(Map<String,Object> ) info.get("skuInfo");
            if(info.getCode()==0){
                wareSkuEntity.setSkuName((String) skuInfo.get("skuName"));
            }
        }catch (Exception e){
            //查询失败的话，就什么都不做
        }
            this.baseMapper.insert(wareSkuEntity);
        }else{
            this.baseMapper.addStock(skuId,wareId,skuNum);
        }

    }

    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {

        List<SkuHasStockVo> collect = skuIds.stream().map(skuId -> {
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
            Long count = baseMapper.getSkuStock(skuId);

            skuHasStockVo.setSkuId(skuId);
            skuHasStockVo.setHasStock(count==null?false:count> 0);
            return skuHasStockVo;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 为某个订单锁定库存
     *
     * 1. 下订单成功，订单过期没有支付被系统自动取消、被用户手动取消，都要解锁库存
     * 2. 下订单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚，之前
     * 锁定的库存解锁
     * @param wareSkuLockVo
     * @return
     */
    @Transactional
    @Override
    public Boolean orderLockStock(WareSkuLockVo wareSkuLockVo) {

        //锁库存之前，保存库存工作单
        WareOrderTaskEntity wareOrderTaskEntity = new WareOrderTaskEntity();
        wareOrderTaskEntity.setOrderSn(wareSkuLockVo.getOrderSn());
        wareOrderTaskService.save(wareOrderTaskEntity);

        //1. 找到每个商品在哪个仓库都有库存
        List<OrderItemVo> locks = wareSkuLockVo.getLocks();

        List<SkuWareHasStock> stocks = locks.stream().map(item -> {
            SkuWareHasStock skuWareHasStock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            skuWareHasStock.setNum(item.getCount());
            skuWareHasStock.setSkuId(skuId);
            List<Long> wareId = this.baseMapper.listWareId(skuId);

            skuWareHasStock.setWareId(wareId);
            return skuWareHasStock;

        }).collect(Collectors.toList());

        //2. 锁定库存
        for (SkuWareHasStock stock : stocks) {
            Boolean skuStocked = false;
            Long skuId = stock.getSkuId();
            List<Long> wareIds = stock.getWareId();

            if( wareIds==null &&wareIds.size()==0){
                //没有任何仓库有库存
                throw new NoStockException(skuId);
            }

            for(Long wareId: wareIds){
              Long count =  this.baseMapper.lockSkuStock(skuId,wareId,stock.getNum());

              if(count == 1){
                  skuStocked = true;

                  //创建库存工作单详情
  WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity(null,skuId,"",stock.getNum(),wareOrderTaskEntity.getId(),wareId,1);
  wareOrderTaskDetailService.save(wareOrderTaskDetailEntity);
  //往队列发送消息
                  StockLockTo stockLockTo = new StockLockTo();
                  stockLockTo.setId(wareOrderTaskEntity.getId());
                  StockDetailTo stockDetailTo = new StockDetailTo();
                  BeanUtils.copyProperties(wareOrderTaskDetailEntity,stockDetailTo);
                  stockLockTo.setStockDetailTo(stockDetailTo);
                  rabbitTemplate.convertAndSend("stock-event-exchange","stock.locked",stockLockTo);
                  break;
              }else{
                  //当前仓库锁失败，重试下一个仓库
              }

            }

            if(!skuStocked){
                throw new NoStockException(skuId);
            }
        }

        //3. 肯定锁定成功了
        return true;
    }

    //解锁库存
    @Override
    public void unlockStock(StockLockTo stockLockTo) {

        StockDetailTo detail = stockLockTo.getStockDetailTo();

        Long detailId = detail.getId();
        //查询detailId在数据库是否存在
        //有：证明库存锁定成功了
        //没有：库存锁定失败，库存回滚了，这种情况无需解锁
        WareOrderTaskDetailEntity detailEntity = wareOrderTaskDetailService.getById(detailId);
        if(detailEntity!=null){
            Long id = stockLockTo.getId(); //库存工作单的id
            WareOrderTaskEntity taskEntity = wareOrderTaskService.getById(id);
            String orderSn = taskEntity.getOrderSn();
            R r = orderFeignService.getOrderStatus(orderSn);

            if(r.getCode() == 0){
                //订单数据成功返回
                Object orderEntity = r.get("orderEntity");
                String s = JSON.toJSONString(orderEntity);
                OrderVo orderVo = JSON.parseObject(s, OrderVo.class);
                if(orderVo ==null || orderVo.getStatus() == 4){
                    //订单不存在的话，也要解锁
                    //订单已经被取消，才能解锁库存
                    if(detailEntity.getLockStatus() == 1){
                        //当前库存工作单详情，状态1已锁定 但是未解锁，才能锁定
                        unLockStock(detail.getSkuId(),detail.getWareId(),detail.getSkuNum(),detailId);
                    }
                }
            }else{
                throw new RuntimeException("远程服务失败");

            }

        }else{

            //无需解锁
        }
    }

    //防止订单出现库存，然后库存这时候去解锁，发现订单状态还是待付款，导致不能释放库存，然后订单这时候取消了

    @Override
    public void unlockStock(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();

       WareOrderTaskEntity entity = wareOrderTaskService.getOrderTaskByOrderSn(orderSn);
        Long id = entity.getId();
        //按照工作单找到 没有解锁的库存， 进行解锁
        List<WareOrderTaskDetailEntity> entities = wareOrderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>().eq("task_id", id).eq("lock_status", 1));

        if(entities!=null){
            for (WareOrderTaskDetailEntity item : entities) {
                unLockStock(item.getSkuId(),item.getWareId(),item.getSkuNum(),item.getId());
            }
        }

    }

    @Data
    class SkuWareHasStock{
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }

}